/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package easybooking.clients.gui.editor;

import easybooking.EBInterface;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.UIManager;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableRowSorter;

/**
 * The Dialog to Select an airline of a plane
 * @author Tim Schröder
 * http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting
 */
public class PlaneDialogAirlineSelect extends JDialog {

    private EBInterface ebi;
    private JLabel lblSearch;
    private JTextField txfSearch;
    private JTable tblAirlines;
    private JPanel buttonPanel;
    private JButton btnSelectAirline;
    private JButton btnCancel;
    private Vector tableData;
    private TableRowSorter<AirlineTableModel> sorter;
    private AirlineTableModel model;
    private JPanel dialogPanel;

    /**
     * Constructor of PlaneDialogAirlineSelect
     * @param ebif an EBInterface object
     */
    public PlaneDialogAirlineSelect(EBInterface ebif) {
        ebi = ebif;
        //tableData = ebi.ebic.getAllTypess();
        //generateComponents();

    }

    /**
     * get the inserted text from the search text field
     * @return the searched text
     */
    public String getSearchText() {
        return txfSearch.getText();
    }

    // gets and returns the selected type from the table / table model
    /**
     * gets and returns the selected airline from the table
     * @return the selected airline
     */
    public Object getSelectedAirline() {
        if (tblAirlines.getSelectedRow() == -1) {
            // returns null if now row is selected
            return null;
        }
        // converts the selected row from the view to the corresponding model row
        int modelRow = tblAirlines.convertRowIndexToModel(tblAirlines.getSelectedRow());
        // gets the type object from the model, this is not good, think about it
        return tblAirlines.getModel().getValueAt(modelRow, 3);
    }

    // sets the data for the type table model 
    public void setTableData(Vector t) {
        tableData = t;

    }

    /**
     * calls the generateComponents() method to create and show the PlaneDialogAirlineSelect
     */
    public void createAndShowDialog() {
        generateComponents();
        this.setResizable(true);
        this.setTitle("Select Airline");
        this.setModal(true); // deaktivates input to other dialogs
        this.setLocationRelativeTo(null);
        this.pack();
        this.setVisible(true);
        this.toFront();

    }

    /**
     * Generates all components to create and display the GUI
     */
    private void generateComponents() {
        dialogPanel = new JPanel();

        // sets system default look and feel
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception exc) {
            System.err.println("Error loading L&F: " + exc);
        }

        // Sets the border
        dialogPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createTitledBorder("Select Airline"),
                BorderFactory.createEmptyBorder(20, 20, 20, 20)));

        dialogPanel.setLayout(new GridBagLayout());
        GridBagLayout gbl = new GridBagLayout();



        lblSearch = new JLabel("Search:");
        // Places the GUI elements in the layout using addComponent                                  x, y, w, h, wx, wy
        addComponent(dialogPanel, gbl, lblSearch, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 0, 0, 1, 1, 0, 0);
        txfSearch = new JTextField(35);

        // registrates the document listener for filtering
        txfSearch.getDocument().addDocumentListener(
                new DocumentListener() {

                    public void changedUpdate(DocumentEvent e) {
                        typeFilter();
                    }

                    public void insertUpdate(DocumentEvent e) {
                        typeFilter();
                    }

                    public void removeUpdate(DocumentEvent e) {
                        typeFilter();
                    }
                });
        // Places the GUI elements in the layout using addComponent                                  x, y, w, h, wx, wy
        addComponent(dialogPanel, gbl, txfSearch, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 0, 1, 1, 0, 0);



        // creates table with type model and data
        tblAirlines = new JTable();
        // gets an instance of the typeTableModel with table data
        model = new AirlineTableModel(tableData);

        // creates the sorter for the table depending on the table model
        sorter = new TableRowSorter<AirlineTableModel>(model);

        // sets the model of tblAirlines
        tblAirlines.setModel(model);

        // adds the sorter to tblAirlines
        tblAirlines.setRowSorter(sorter);

        // allows only a single selection on the table
        tblAirlines.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);



        // adds the table within a scroll pane to the layout
        // Places the GUI elements in the layout using addComponent                                                x, y, w, h, wx, wy
        addComponent(dialogPanel, gbl, new JScrollPane(tblAirlines), GridBagConstraints.BOTH, GridBagConstraints.CENTER, 0, 1, 3, 1, 1, 1);


        // adds the buttton panel to the layout
        // Places the GUI elements in the layout using addComponent                                                 x, y, w, h, wx, wy
        addComponent(dialogPanel, gbl, this.createButtonPanel(), GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 0, 2, 3, 1, 0, 0);

        this.setContentPane(dialogPanel);

    }

    /**
     * Creates a tablerowfilter for the airlineTableModle based on ragular expressions and adds it to the sorter
     */
    private void typeFilter() {
        RowFilter<AirlineTableModel, Object> rf = null;
        //If current expression doesn't parse, don't update.
        try {
            //                                              columns included in filter
            rf = RowFilter.regexFilter(txfSearch.getText(), 0, 1, 2, 3, 4, 5);

        } catch (java.util.regex.PatternSyntaxException e) {
            return;
        }
        sorter.setRowFilter(rf);
    }

    /**
     * Creates the buttons to select a airline or cancel
     * @return a JPanel with 2 buttons
     */
    private JPanel createButtonPanel() {

        buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridBagLayout());
        GridBagLayout gbl = new GridBagLayout();

        btnSelectAirline = new JButton("Select Airline");
        btnSelectAirline.setActionCommand("PlaneSelectAirline");
        btnSelectAirline.addActionListener(ebi);



        btnCancel = new JButton("Cancel");
        btnCancel.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });

        // Sets the buttons the same size
        btnCancel.setPreferredSize(btnSelectAirline.getPreferredSize());

        // Adds the buttons to the buttonPanel
        addComponent(buttonPanel, gbl, btnSelectAirline, GridBagConstraints.NONE, GridBagConstraints.WEST, 0, 0, 1, 1, 1, 0);
        addComponent(buttonPanel, gbl, btnCancel, GridBagConstraints.NONE, GridBagConstraints.EAST, 1, 0, 1, 1, 0, 0);

        return buttonPanel;
    }

    /**
     * defines the layout of the GUI
     * @param cont container to which the component is added
     * @param gbl GridBagLayout object
     * @param c compontent which is added to the container
     * @param fill how to use free space in the cell around the component
     * @param anchor where to fix an align the component
     * @param x x position in the grid layout
     * @param y y position in the grid layout
     * @param width number of columns the element should spread
     * @param hight number of rows the element should spread
     * @param weightx handels the horizontal free space
     * @param weighty handels the vertical free space
     */
    private static void addComponent(Container cont, GridBagLayout gbl, Component c, int fill, int anchor, int x, int y, int width, int hight, double weightx, double weighty) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = fill;
        gbc.anchor = anchor;
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridwidth = width;
        gbc.gridheight = hight;
        gbc.weightx = weightx;
        gbc.weighty = weighty;
        gbc.insets = new Insets(10, 10, 10, 10);
        //gbl.setConstraints(c, gbc);
        cont.add(c, gbc);


    }
}
